package com.goresor.controller.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.openid.OpenIDAttribute;
import org.springframework.security.openid.OpenIDAuthenticationStatus;
import org.springframework.security.openid.OpenIDAuthenticationToken;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import com.goresor.service.IUserService;

public class OpenIDAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	private static final String USER_OPENID_EMAIL = "USER_OPENID_EMAIL";
	private static final String USER_OPENID_USERID = "USER_OPENID_USERID";
	
	public static final Logger log = LoggerFactory.getLogger(OpenIDAuthenticationFailureHandler.class);

	@Autowired
	private IUserService userService;
	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {

		log.info("erreur d'authentification !");

		if (exception instanceof UsernameNotFoundException) {
			
			boolean isOpenIdIdentification = exception.getAuthentication() instanceof OpenIDAuthenticationToken;
			boolean isOpenIdAuthentified = ((OpenIDAuthenticationToken) exception.getAuthentication()).getStatus().equals(
					OpenIDAuthenticationStatus.SUCCESS);

			log.info("openIdidentification :" + isOpenIdIdentification);
			log.info("openIdAuthentified:" + isOpenIdAuthentified);

			if (isOpenIdIdentification && isOpenIdAuthentified) {
				log.info("authent:"+exception.getAuthentication());
				
				String principal = (String)((OpenIDAuthenticationToken) exception.getAuthentication()).getPrincipal();
				String googleUserId = principal.substring(principal.indexOf("id=")+3);
				request.getSession(true).setAttribute(USER_OPENID_EMAIL, ((OpenIDAttribute)((OpenIDAuthenticationToken)((UsernameNotFoundException) exception).getAuthentication()).getAttributes().get(0)).getValues().get(0));
				request.getSession(true).setAttribute(USER_OPENID_USERID,googleUserId);
				
				// redirect to create account page
				String email = (String) request.getSession().getAttribute(USER_OPENID_EMAIL);
				String userId = (String) request.getSession().getAttribute(USER_OPENID_USERID);
				
				if (email != null) {
					userService.createUser(userId, "unused", email);
					log.info("Your account has been created. Please log using your OpenID.");
				}
			}
			return;
		}
		super.onAuthenticationFailure(request, response, exception);
	}
}